<template>
  <div class="week-calendar-container">
    <div style="border: 1px solid rgb(183, 197, 243); width: 100%;border-radius: 8px;box-shadow: 0 0 10px 5px rgb(229, 233, 251);">
      <!-- 星期 -->
      <div style="display: flex;justify-content: space-around;font-size: 18px;padding-top: 19px;">
        <div v-for="(day, index) in weekDays" :key="index" style="width: 13%;text-align: center;">
          {{ day }}
        </div>
      </div>

      <!-- 日期行 -->
      <div style="display: flex;justify-content: space-around;padding-top: 10px;position: relative;">
        <!-- 左按钮 -->
        <div class="week-nav-button left" @click="prevWeek">
          <i class="el-icon-arrow-left"></i>
        </div>

        <!-- 日期格子 -->
        <div v-for="(date, index) in currentWeekDates"
             :key="index"
             style="width: 13%;text-align: center; padding-bottom: 15px;"
             @click="selectDate(date)">
          <!-- 核心：只有一个 class 会生效，选中即高亮 -->
          <div :class="cellClass(date)"
               style="width: 35px;margin: auto;border-radius: 5px;padding: 5px 3px;cursor: pointer;">
            <div class="date-number">{{ date.day }}</div>
            <div class="date-lunar">{{ date.lunar }}</div>
          </div>
        </div>

        <!-- 右按钮 -->
        <div class="week-nav-button right" @click="nextWeek">
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getLunarDate } from '@/utils/lunarCalendar';

export default {
  name: 'WeekCalendar',
  props: {
    initialDate: {
      type: String,
      default: null
    },
    showNavButtons: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      currentWeekDates: [],
      selectedDate: null,
      currentWeekStart: null
    };
  },
  created() {
    this.initCalendar();
  },
  methods: {
    /* ----------------- 初始化 ----------------- */
    initCalendar() {
      const today = new Date();
      let startDate;

      if (this.initialDate) {
        const initDate = new Date(this.initialDate);
        const dayOfWeek = initDate.getDay();
        startDate = new Date(initDate);
        startDate.setDate(initDate.getDate() - (dayOfWeek === 0 ? 0 : dayOfWeek));
      } else {
        const dayOfWeek = today.getDay();
        startDate = new Date(today);
        startDate.setDate(today.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));
      }

      this.currentWeekStart = startDate;
      this.generateCurrentWeekDates();

      if (this.initialDate) {
        this.selectedDate = this.initialDate;
      } else {
        const todayStr = this.formatDate(today);
        this.selectedDate = this.currentWeekDates.some(d => d.fullDate === todayStr)
          ? todayStr
          : this.currentWeekDates[0].fullDate;
      }

      this.$emit('date-selected', this.selectedDate);
    },

    /* ----------------- 生成 7 天 ----------------- */
    generateCurrentWeekDates() {
      const weekDates = [];
      const start = new Date(this.currentWeekStart);
      for (let i = 0; i < 7; i++) {
        const date = new Date(start);
        date.setDate(start.getDate() + i);
        weekDates.push({
          day: date.getDate(),
          lunar: getLunarDate(date),
          fullDate: this.formatDate(date),
          dateObj: date
        });
      }
      this.currentWeekDates = weekDates;
    },

    /* ----------------- 选择日期 ----------------- */
    selectDate(date) {
      this.selectedDate = date.fullDate;
      this.$emit('date-selected', this.selectedDate);
    },

    /* ----------------- 工具函数 ----------------- */
    isToday(dateStr) {
      return dateStr === this.formatDate(new Date());
    },
    isSelected(dateStr) {
      return this.selectedDate === dateStr;
    },
    formatDate(date) {
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      return `${y}-${m}-${d}`;
    },

    /* ----------------- 周切换 ----------------- */
    prevWeek() {
      const newStart = new Date(this.currentWeekStart);
      newStart.setDate(newStart.getDate() - 7);
      this.currentWeekStart = newStart;
      this.generateCurrentWeekDates();
      this.selectedDate = this.currentWeekDates[6].fullDate; // 默认周日
      this.$emit('date-selected', this.selectedDate);
      this.$emit('week-changed', {
        start: this.currentWeekDates[0].fullDate,
        end: this.currentWeekDates[6].fullDate,
        currentSelected: this.selectedDate
      });
    },
    nextWeek() {
      const newStart = new Date(this.currentWeekStart);
      newStart.setDate(newStart.getDate() + 7);
      this.currentWeekStart = newStart;
      this.generateCurrentWeekDates();
      this.selectedDate = this.currentWeekDates[0].fullDate; // 默认周一
      this.$emit('date-selected', this.selectedDate);
      this.$emit('week-changed', {
        start: this.currentWeekDates[0].fullDate,
        end: this.currentWeekDates[6].fullDate,
        currentSelected: this.selectedDate
      });
    },

    /* ----------------- 计算日期格子 class ----------------- */
    cellClass(date) {
      // 被选中的优先级最高，today 仅在没有选中时生效（可选）
      return {
        'selected-date': this.isSelected(date.fullDate),
        'today-header': !this.isSelected(date.fullDate) && this.isToday(date.fullDate)
      };
    }
  },
  watch: {
    initialDate(newVal) {
      if (newVal) this.initCalendar();
    }
  }
};
</script>

<style scoped>
.week-calendar-container {
  font-family: Arial, sans-serif;
}

.week-nav-button {
  position: absolute;
  top: 5%;
  width: 24px;
  height: 24px;
  background: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1;
  color: #4C6EE2;
}
.week-nav-button:hover {
  background: #f5f7fa;
}
.week-nav-button.left {
  left: -12px;
}
.week-nav-button.right {
  right: -12px;
}

/* 今天默认样式，可被 selected 覆盖 */
.today-header {
  background-color: rgba(76, 110, 226, 0.2);
  color: #4C6EE2;
}

/* 选中后强制覆盖 */
.selected-date {
  background-color: #4C6EE2 !important;
  color: white !important;
}

.date-number {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}
.date-lunar {
  font-size: 12px;
  color: inherit;
}
</style>